package com.chandon.juc.thread_communication.AlternatePrinting;

import java.util.concurrent.FutureTask;

/**
 * 2个线程交替打印A与B，重复n次
 *
 * @author Dong
 */
public class UseWaitNotify {
	public static void main(String[] args) throws InterruptedException {

		int count = 0;

		while (count < 10) {
			useWait();
			count++;
			Thread.sleep(4000);
		}
		System.out.println("执行完成");


	}


	public static void  useWaitNotifyFutureTask(){

		FutureTask<Object> futureTaskA = new FutureTask<Object>(() -> {

			for (int i = 0; i < 50; i++) {

				synchronized (o) {
					System.out.println(Thread.currentThread().getName() + "----A:" + (i));
					try {
						o.notify();
						o.wait();
					} catch (InterruptedException e) {
						throw new RuntimeException(e);
					}
				}
			}
			return null;
		});


		FutureTask<Object> futureTaskB = new FutureTask<Object>(() -> {

			for (int i = 0; i < 50; i++) {

				synchronized (o) {
					try {
						o.wait();
					} catch (InterruptedException e) {
						throw new RuntimeException(e);
					}
					System.out.println(Thread.currentThread().getName() + "----B:" + (i));
					o.notify();
				}
			}


			return null;
		});




	}

	static Object o = new Object();


	/**
	 * 必须b线程先于a线程执行，否则死锁
	 */
	public static void useWait() {

		Thread threadA = new Thread() {
			@Override
			public void run() {


				for (int i = 0; i < 50; i++) {

					synchronized (o) {
						System.out.println(Thread.currentThread().getName() + "----A:" + (i));
						try {
							o.notify();
							o.wait();
						} catch (InterruptedException e) {
							throw new RuntimeException(e);
						}
					}

				}

			}
		};


		Thread threadB = new Thread() {

			@Override
			public void run() {


				for (int i = 0; i < 50; i++) {

					synchronized (o) {
						try {
							o.wait();
						} catch (InterruptedException e) {
							throw new RuntimeException(e);
						}
						System.out.println(Thread.currentThread().getName() + "----B:" + (i));
						o.notify();
					}
				}
				System.out.println("--------------------------------");
			}
		};

		threadB.start();
		threadA.start();


	}
}
